<?php

namespace app\Http\Controllers\admins;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class home extends Controller
{
    public function index(Request $request)
    {
        $admin = $request->admin;
        // 系统设置
        $setting = DB::table('setting')->where('names', 'setting')->first();
        $setting = isset($setting->values) ? json_decode($setting->values) : null;
        $admin->avatar = $admin->avatar ?? ($setting->avatar ?? '');
        $data['admin'] = $admin;
        $menus = DB::table('admin_menus')
            ->where('ishidden', 0)
            ->where('status', 0)
            ->orderBy('id', 'asc')
            ->orderBy('ord', 'desc')
            ->whereIn('id', $admin->rights)
            ->get()
            ->all();
        $menus = $this->levels($menus);
        $data['menus'] = $this->menus($menus);
        return view('/admins/home/index', $data);
    }

    public function welcome()
    {
        return view('/admins/home/welcome');
    }

    // 无限级菜单
    private function menus($datas)
    {
        $res = '';
        foreach ($datas as $k => $data) {
            $res .= $this->children($data, $k);
        }
        return $res;
    }

    // 递归子数据
    private function children($data, $k = 0, $indent = 0)
    {
        $res = '';
        if ($data->children) {
            $res .= sprintf('<li class="layui-nav-item%s">', $k === 0 ? ' layui-nav-itemed' : '');
            $res .= sprintf('<a href="javascript:;" style="text-indent:%dem;" title="%s">%s</a>', max($indent - 1, 0), strip_tags($data->title), $data->title);
            $res .= '<dl class="layui-nav-child">';
            foreach ($data->children as $k => $data) {
                if ($data->children) {
                    $res .= $this->children($data, $k, $indent + 1);
                } else {
                    $res .= sprintf('<dd><a href="javascript:;" style="text-indent:%dem;" controller="%s" action="%s" onclick="firemenu(this)" title="%s">%s</a></dd>', $indent, $data->controller, $data->action, strip_tags($data->title), $data->title);
                }
            }
            $res .= '</dl>';
            $res .= "</li>\n";
        } else {
            $res .= sprintf('<li class="layui-nav-item%s"><a href="javascript:;" controller="%s" action="%s" onclick="firemenu(this)" title="%s">%s</a></li>', $k === 0 ? ' layui-this' : '', $data->controller, $data->action, strip_tags($data->title), $data->title);
        }
        return $res;
    }
}
